package com.suixinsanren.design.command.demo03;

public class RemoteControl {

    private final Command[] onCommands;
    private final Command[] offCommands;
    private Command undoCommand;

    public RemoteControl(int slot) {
        initCheckSlot(slot);

        onCommands = new Command[slot];
        offCommands = new Command[slot];
        undoCommand = new NoCommand();
    }

    public void setCommand(int slot, Command onCommand, Command offCommand) {
        checkSlot(slot);
        this.onCommands[slot] = onCommand;
        this.offCommands[slot] = offCommand;
    }

    public void onButtonWasPushed(int slot) {
        checkSlot(slot);
        onCommands[slot].execute();
        undoCommand = onCommands[slot];
    }

    public void offButtonWasPushed(int slot) {
        checkSlot(slot);
        offCommands[slot].execute();
        undoCommand = offCommands[slot];
    }

    public void undo() {
        undoCommand.undo();
    }

    private void initCheckSlot(int slot) {
        if (slot <= 0) {
            throw new IllegalArgumentException("槽数不合法");
        }
    }

    private void checkSlot(int slot) {
        if (slot < 0) {
            throw new IllegalArgumentException("槽数不合法");
        }
    }
}
